import os
from datetime import datetime
import json
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import create_engine, exc
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from Model.api_call_log import ApiCallLog
from Model.api_call_statistics import ApiCallStatistics
from Model.status import Status

from volcengine.ApiInfo import ApiInfo
from volcengine.Credentials import Credentials
from volcengine.ServiceInfo import ServiceInfo
from volcengine.base.Service import Service

db_path = os.path.join(os.getcwd(), 'DB', 'ai_proj.db')
def read_config():
    config_path = './config.json'
    ak = sk = None
    try:
        with open('config.json', 'r') as f:
            config = json.load(f)
            ak = config.get('ak', '')
            sk = config.get('sk', '')
    except FileNotFoundError:
        print(f"警告: config.json不存在，请检查文件路径。")

    return ak, sk

ak, sk = read_config()

def translate_texts(texts):
    engine = create_engine(f'sqlite:///{db_path}')
    Session = sessionmaker(bind = engine)
    session = Session()

    k_service_info = ServiceInfo(
        "translate.volcengineapi.com", 
        {'Content-Type': 'application/json'},
        Credentials(ak, sk, 'translate', 'cn-north-1'), 
        5,
        5)
    k_query = {
        'Action': 'TranslateText',
        'Version': '2020-06-01'
    }
    k_api_info = {
        'translate': ApiInfo('POST', '/', k_query, {}, {})
    }
    service = Service(k_service_info, k_api_info)
    body = {
        'TargetLanguage': 'zh',
        'TextList': texts,
    }

    curTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    status = Status.SUCCESS
    tranlateCnt = sum(len(str) for str in texts)

    try:
        res = service.json('translate', {}, json.dumps(body))
        status = Status.SUCCESS
        errInfo = " "
    except Exception as e:
        print(f"Error creating Api: {e}")
        status = Status.FAILURE
        errInfo = str(e)           

    try: 
        addNewLog(session, curTime, status, tranlateCnt, errInfo)
        successCnt = 1 if status == Status.SUCCESS else 0
        failureCnt = 1 if status == Status.FAILURE else 0
        addStatistics(session, successCnt, failureCnt, tranlateCnt)

        session.commit()
    except Exception as e:
        print(f"Error creating ApiCallLog: {e}")
        session.rollback()
        return

    print("Successfully added new log.")
    res_dict = json.loads(res)
    translate_result = [item.get('Translation', '') for item in res_dict.get('TranslationList', [])]
    return translate_result

def batch_translate(lines, max_batch_size = 16, max_chars = 5000):
    """ 批量翻译文本 """
    translations = []
    current_batch = []
    current_char_count = 0

    for line in lines:
        if len(current_batch) < max_batch_size and current_char_count + len(line) <= max_chars:
            current_batch.append(line)
            current_char_count += len(line)
        else:
            translations.extend(translate_texts(current_batch))
            current_batch = [line]
            current_char_count = len(line)

    if current_batch:
        translations.extend(translate_texts(current_batch))

    return translations

def process_file(input_path, output_path):
    """ 处理文件，替换特定行的内容为翻译后的内容 """
    with open(input_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 获取所有需要翻译的第三行
    lines_to_translate = [lines[i].strip() for i in range(2, len(lines), 4)]

    # 批量翻译
    translated_lines = batch_translate(lines_to_translate)

    # 替换原文件中的内容
    translated_index = 0
    new_lines = []
    for i in range(len(lines)):
        if (i + 1) % 4 == 3 and translated_index < len(translated_lines):
            new_lines.append(translated_lines[translated_index] + '\n')
            translated_index += 1
        else:
            new_lines.append(lines[i])

    # 写入新文件
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    with open(output_path, 'w', encoding='utf-8') as file:
        file.writelines(new_lines)

def addNewLog(session, call_time, status, translated_chars, err_Info):
    try:
        createTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        new_log = ApiCallLog(
            call_time= call_time ,
            # 获取当前时间，格式化为"YYYY-MM-DD HH:MM:SS"
            created_at= createTime,
            status = status,
            translated_chars = translated_chars,
            error_info = err_Info
        )
        session.add(new_log)
    except Exception as e:
        print(f"Error creating ApiCallLog: {e}")
        return
    
def addStatistics(session, success_count, failure_count, total_translated_chars):
    try:
        # 如果当天的记录已经存在，则更新该记录，否则创建新记录
        queryDate = datetime.now().strftime("%Y-%m-%d")
        # 查询当天的记录
        existing_record = session.query(ApiCallStatistics).filter_by(cur_date = queryDate).first()

        if existing_record:
            # 更新现有记录
            existing_record.success_count += success_count
            existing_record.failure_count += failure_count
            existing_record.total_translated_chars += total_translated_chars
        else:
            # 创建新记录
            new_statistics = ApiCallStatistics(
                cur_year = datetime.now().year,
                cur_month = datetime.now().month,
                cur_date = datetime.now().strftime("%Y-%m-%d"),
                success_count = success_count,
                failure_count = failure_count,
                total_translated_chars = total_translated_chars
            )
            session.add(new_statistics)

        # 提交事务
        # session.commit()
    except SQLAlchemyError as e:
        # 回滚事务并处理异常
        # session.rollback()
        print(f"Error creating ApiCallStatistics: {e}")
        return